<template>
	<view class="w100 bg-white relative pb-40" style="border-radius: 10px 10px 0px 0px;">
		<view class="center ptb-30 bb bold">待支付金额</view>
		<u-icon @click="close" name="close" class="absolute size-32" style="left: 30rpx; top: 34rpx;"></u-icon>
		<view class="ml-40 pr-40 mt-30 pb-30 bb">
			<view class="flexz">
				<view class="">
					{{info.sf_type?'总计费用':'总计费用'}}
				</view>
				<view class="">
					{{info.sf_type?info.order_money:price1.toFixed(2)}}
				</view>
			</view>
			<view class="flexz mt-10" v-if="!info.sf_type && 0">
				<view class="">
					等待费
				</view>
				<view class="">
					{{info.overtime_price || 0}}
				</view>
			</view>
			<!-- <view class="flex size-26 mt-10">
				<view class="red">
					优惠券
				</view>
				<view class="" @click="toCoupon">
					<text class="gray-1" v-if="!coupon.id">{{userInfo.coupon_count}}张</text>
					<text class="red" v-else>-{{coupon.price}}</text>
					<u-icon name="arrow-right" class="gray-2 ml-10"></u-icon>
				</view>
			</view> -->
		</view>

		<view class="plr-60 center mt-10">
			<view class="red" v-if="!coupon.id">
				￥<text class="size-42 bold">{{info.sf_type?info.order_money:info.price}}</text>
			</view>
			<view class="red" v-else>
				￥<text class="size-42 bold">{{price}}</text>
			</view>
			<!-- <view class="">
				<text>费用明细</text>
				<u-icon name="arrow-right" class="gray-2 ml-10"></u-icon>
			</view> -->
		</view>
		<view class="wanl-pay">
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index">
					<text :class="'wlIcon-'+ item.type +'-pay'"></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<view v-if="item.type == 'balance'">
							<text>可用余额 ￥{{user.money}}</text>
						</view>
						<view v-else>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
			</view>
		</view>
		<view class="plr-36 mt-40">

			<u-button type="primary" @click="confirm()">确认支付</u-button>
		</view>
		<uni-popup ref="popup" type="bottom">
			<view class="popup-modal">
				<view>
					<view class="auth">
						<view class="auth-title" style="padding-top: 30rpx">输入支付密码</view>
						<view class="codes">
							<view v-for="item in config.count" :key="item.key">
								<view class="input" @tap="hanldeOpenKeyboard"
									:class="{ active: currentFocus == item.index }">
									<template v-if="code[item.index - 1] != undefined">
										<!-- {{ code[item.index - 1] }} -->*
									</template>
									<template v-else>
										<view v-if="currentFocus == item.index" class="shining"></view>
									</template>
								</view>
							</view>
						</view>
					</view>
					<wanl-keyboards :open="keyboardVisible" @number="inputCode" @delete="deleteCode"
						@empty="emptyCode" />
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script>
	import NP from '@/uni_modules/number-precision'
	import {
		mapState
	} from 'vuex'
	export default {
		props: ['info'],
		data() {
			return {
				value: '2',
				coupon: {},
				payList: [],
				isbalance:false,
				config: {
					count: [{
							index: 1,
							key: 'valid-code-input-1'
						},
						{
							index: 2,
							key: 'valid-code-input-2'
						},
						{
							index: 3,
							key: 'valid-code-input-3'
						},
						{
							index: 4,
							key: 'valid-code-input-4'
						},
						{
							index: 5,
							key: 'valid-code-input-5'
						},
						{
							index: 6,
							key: 'valid-code-input-6'
						}
					]
				},
				keyboardVisible: true,
				currentFocus: 1,
				code: [],
			}
		},
		computed: {
			...mapState(["userInfo", 'user']),
			price() {
				return this.info.sf_type ? NP.minus(this.info.order_money, this.coupon.price || 0) : NP.minus(this.info.price, this.coupon.price || 0)
			},
			price1() {
				return this.info.sf_type ? 0 : NP.minus(this.info.price, this.info.overtime_price || 0)
			}
		},
		mounted() {
			console.log('价格表单', this.info);
			uni.$on("coupon", (option) => {
				console.log(option);
				this.coupon = option
			})
			let price = this.info.sf_type?this.info.order_money:this.info.price
			if(price<= parseFloat(this.$store.state.user.money)){
				this.isbalance = true;
				this.getPayment();
			}
			uni.request({
				url: '/wanlshop/pay/getBalance',
				method: 'POST',
				success: res => {
					this.$store.commit('user/setUserInfo', {money: res.data});
					// 获取支付列表
					this.getPayment();
				}
			});
		},
		destroyed() {
			uni.$off("coupon")
		},
		methods: {
			getPayment() {
				let method = 'app';
				// #ifdef APP-PLUS
				method = 'app';
				// #endif
				// #ifdef MP-WEIXIN
				method = 'miniapp';
				// #endif
					this.payList = [{
						name: '余额支付',
						describe: '',
						type: 'balance',
						method: method,
						state: true,
						select: this.isbalance ? true : false // 是否选中
					}, {
						name: '支付宝',
						describe: '',
						type: 'alipay',
						method: method,
						state: true,
						select: false
					}, {
						name: '微信支付',
						describe: '推荐使用微信支付',
						type: 'wechat',
						method: method,
						state: true,
						select: this.isbalance ? false : true
					}];
					console.log("支付方式",this.payList)
			},
			onSelect(key){
				this.payList.map((value,index,array) => {
				　　if(index == key){
						value.select = !value.select;
					}else{
						value.select = false;
					}
				});
			},
			close() {
				
				this.$emit('close')
				setTimeout(()=>{
					uni.navigateBack({
						delta:1
					})
				},2000)
			},
			radioGroupChange(e) {
				console.log(e);
				this.value = e
			},
			submit() {
				let _this = this
				//微信支付
				// #ifdef MP-WEIXIN
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {

						console.log(loginRes);
						_this.pay(loginRes.code)
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				this.pay()
				// #endif
			},
			
			//确认支付
			confirm() {
				let data = null;
				if (this.disabled) {
					return;
				}
				this.payList.map((value,index,array) => {
				　　if(value.select){
						data = value;
					}else{
						return;
					}
				});
				// 判断支付是否存在
				if (!data) {
					uni.showModal({
					    content: "请选择支付方式",
					    showCancel: false
					});
					return;
				}else{
					console.log(data)
					if(data.type == 'balance' || data.type == 'point') {
						this.payMethod = data.method
						this.payType = data.type
						this.$refs.popup.open('bottom');
					} else {
						this.disabled = true;
						// 获取小程序code
						// #ifdef MP
						uni.login({
						    success: (e) => {
								this.wanlPay(data, e.code);
						    },
						    fail: (e) => {
						        uni.showModal({
						            content: "无法获取微信code,原因为: " + e.errMsg,
						            showCancel: false
						        })
						    }
						})
						// #endif
						// #ifndef MP
						// 如果是公众号获取code
						this.wanlPay(data);
						// #endif
					}
				}
			},
			async wanlPay(data, code = null){
				let datas = await uni.request({url: '/publics/commons/getToken',method: 'POST',data:{type:`ddcar_order_pay`}})
				let _this = this
				await uni.request({
					url: '/payment/pay/index',
					method: 'POST',
					data: {
						pay_type: data.type,
						method: data.method,
						order_id: this.info.id,
						wxcode: code,
						pay_pass: data.pay_pass,
						order_type: 'ddcar',
						token: datas[1].data
					},
					success: res => {
						// 余额支付/小程序支付
						switch (data.type) {
						    case 'balance':
						        this.$store.commit('user/setUserInfo', {
						        	money: this.$wanlshop.bcsub(this.$store.state.user.money, this.price)
						        });
						        uni.showToast({
						        	title: '支付成功'
						        })
						        _this.close()
						        _this.$emit('update')
						        break;
							case 'point':
							    uni.showToast({
							    	title: '支付成功'
							    })
							    _this.close()
							    _this.$emit('update')
							    break;
						    case 'wechat':
								// 微信 H5支付
						        if(data.method == 'wap'){
						        	setTimeout(() => {
						        		uni.showModal({
						        		    content: '请确认微信支付是否已完成',
						        			confirmText: '已完成',
						        			cancelText: '重新支付',
						        		    success: response=> {
						        		        if (response.confirm) {
						        		            uni.showToast({
						        		            	title: '支付成功'
						        		            })
						        		            _this.close()
						        		            _this.$emit('update')
						        		        } else if (response.cancel) {
						        		            this.confirm();
						        		        }
						        		    }
						        		});
						        	}, 2000);
						        	// 异步查询是否支付成功
						        	window.location.href = res.data;
								// 微信 APP支付
								}else if(data.method == 'app'){
									uni.requestPayment({
									    provider: 'wxpay',
									    orderInfo: res.data.data,
									    success: (e) => {
									        console.log("success", e);
									        uni.showToast({
									        	title: '支付成功'
									        })
									        _this.close()
									        _this.$emit('update')
									    },
									    fail: (e) => {
									        uni.showModal({
									            content: "支付失败,原因为: " + e.errMsg,
									            showCancel: false
									        })
									    },
									    complete: () => {
											this.disabled = false;
									    }
									})
								// 微信 小程序支付
						        }else if(data.method == 'miniapp'){
									uni.requestPayment({
									    appId: res.data.appId,
									    nonceStr: res.data.nonceStr,
									    package: res.data.package,
									    paySign: res.data.paySign,
										signType: res.data.signType,
										timeStamp: res.data.timeStamp,
									    success: (e) => {
									        uni.showToast({
									        	title: '支付成功'
									        })
									        _this.close()
									        _this.$emit('update')
									    },
									    fail: (e) => {
									        uni.showModal({
									            content: "支付失败,原因为: " + e.errMsg,
									            showCancel: false
									        })
									    }
									})
								// 微信 公众平台支付
								}else if(data.method == 'mp'){
									this.$jssdk.wxpay({
										data: res.data,
										success: e => {
											uni.showToast({
												title: '支付成功'
											})
											_this.close()
											_this.$emit('update')
										},
										fail: err => {
											if (err.errMsg == "chooseWXPay:ok") {
												this.$wanlshop.msg('支付成功');
											}else if (err.errMsg == "chooseWXPay:cancel") {
												this.$wanlshop.msg('支付失败，取消支付');
											}else if (err.errMsg == "chooseWXPay:fail") {
												this.$wanlshop.msg('支付失败');
											}
										}
									})
								}
						        break;
						    case 'alipay':
						        if(data.method == 'wap'){
									this.disabled = false;
									if(this.order_type === 'goods'){
										this.$store.commit('statistics/order', {
											pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
											delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
										});
									}
									document.write(res.data);
								}else if(data.method == 'app'){
									uni.requestPayment({
									    provider: 'alipay',
									    orderInfo: res.data.data,
									    success: (e) => {
									        console.log("success", e);
									        uni.showToast({
									        	title: '支付成功'
									        })
									        _this.close()
									        _this.$emit('update')
									    },
									    fail: (e) => {
									        this.$wanlshop.msg(JSON.stringify(e))
									    },
									    complete: (e) => {
											this.disabled = false;
									    }
									})
								}
								break;
						} 
					},
					fail: () => {
						this.disabled = false;
					}
				});
			},
			onSelect(key){
				this.payList.map((value,index,array) => {
				　　if(index == key){
						value.select = !value.select;
					}else{
						value.select = false;
					}
				});
			},
			inputCode(e) {
				this.code[this.currentFocus - 1] = e;
				if (this.currentFocus == 6) {
					this.wanlPay({
						pay_pass:this.code.join("").replace(/,/g, ''),
						type:this.payType,
						method: this.payMethod
					});
					this.$refs.popup.close('bottom');
					this.emptyCode()
				}
				if (this.currentFocus <= 6) {
					this.currentFocus++;
				}
			},
			deleteCode() {
				this.currentFocus--;
				this.code.splice(-1, 1);
			},
			emptyCode() {
				this.code = [];
				this.currentFocus = 0;
			},
			hanldeOpenKeyboard() {
				this.keyboardVisible = true;
			},
			toCoupon() {
				uni.navigateTo({
					url: '/pages/transport/my/coupon/list?sf_type=' + this.info.sf_type + '&id=' + this.info.id
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.u-primary-hover {
		background: linear-gradient(to right, #00b6b4, #00d496) !important;
	}

	/deep/.u-radio-group {
		width: 100% !important;
	}

	/deep/.u-radio {
		width: 100% !important;
		display: flex;
		flex-direction: row-reverse;
		justify-content: space-between;
	}

	image {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
	}
	/deep/.fade-out.uni-transition {
		background: rgba(0, 0, 0, .4) !important;
	}
	
	.popup-modal {
		background-color: #fff;
		height: 900rpx;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
	
	}
	@import url("@/pages/user/auth/auth.css");
</style>